import React, { useState, useEffect } from 'react';
import { Fade, IconButton, Box, keyframes } from '@mui/material';
import KeyboardArrowUpSharpIcon from '@mui/icons-material/KeyboardArrowUpSharp';

// Stronger pulsate effect
const pulsate = keyframes`
  0% {
    transform: scale(1);
    opacity: 0.5;
  }
  50% {
    transform: scale(1.15);
    opacity: 1;
  }
  100% {
    transform: scale(1);
    opacity: 0.5;
  }
`;

const ScrollToTop = ({
  threshold = 100,
  position = {
    bottom: 20,
    right: 20
  },
}) => {
  const [visible, setVisible] = useState(false);

  useEffect(() => {
    const scrollContainer = document.getElementById('scrollable-container');

    const handleScroll = () => {
      if (!scrollContainer) return;
      const scrolled = scrollContainer.scrollTop;
      setVisible(scrolled > threshold);
    };

    if (scrollContainer) {
      scrollContainer.addEventListener('scroll', handleScroll);
    }

    return () => {
      if (scrollContainer) {
        scrollContainer.removeEventListener('scroll', handleScroll);
      }
    };
  }, [threshold]);

  const scrollToTop = () => {
    const scrollContainer = document.getElementById('scrollable-container');
    if (scrollContainer) {
      scrollContainer.scrollTo({ top: 0, behavior: 'smooth' });
    } else {
      window.scrollTo({ top: 0, behavior: 'smooth' });
    }
  };

  return (
    <Box
      sx={{
        position: 'fixed',
        bottom: position.bottom,
        right: position.right,
        zIndex: 3000,
      }}
    >
      <Fade in={visible}>
        <IconButton
          onClick={scrollToTop}
          aria-label="scroll to top"
          sx={{
            animation: `${pulsate} 1s ease-in-out infinite`,
            '& .MuiSvgIcon-root': {
              fontSize: '2rem',
            },
          }}
        >
          <KeyboardArrowUpSharpIcon />
        </IconButton>
      </Fade>
    </Box>
  );
};

export default ScrollToTop;